package com.gzone.contentprovider.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class XMLUtil {

	public static String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if (nl != null && nl.getLength() > 0) {
			Element el = (Element) nl.item(0);
			if(el.hasChildNodes()){
				textVal = el.getFirstChild().getNodeValue();
			}
		}

		return textVal;
	}

	public static int getIntValue(Element ele, String tagName) {
		return Integer.parseInt(getTextValue(ele, tagName));
	}

	public static double getDoubleValue(Element ele, String tagName) {
		return Double.parseDouble(getTextValue(ele, tagName));
	}

	public static boolean getBooleanValue(Element ele, String tagName) {
		String value = getTextValue(ele, tagName);
		if (value == null)
			return false;
		value = value.toLowerCase().trim();
		if (value.equals("true"))
			return true;
		return false;
	}

	public static Document parseXml(String xmlStr) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			ByteArrayInputStream bis = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
			Document dom = db.parse(bis);
			return dom;
		} catch (Exception ioe) {
			// ioe.printStackTrace();
			// System.out.println(xmlStr);
		}
		return null;
	}

	public static Document parseXml(InputStream xmlStr) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document dom = db.parse(xmlStr);
			return dom;
		} catch (Exception ioe) {
			// ioe.printStackTrace();
			// System.out.println(xmlStr);
		}
		return null;
	}

	public static String getElementAtributeValue(Element ele, String eleName, String eleAtribute) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(eleName);
		if (nl != null && nl.getLength() > 0) {
			Element el = (Element) nl.item(0);
			if (el != null)
				return el.getAttribute(eleAtribute);
		}
		return null;
	}
}